<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <h2>1</h2>
    <div id="app">
        <h1>{count}</h1>
    </div>
    <button>点击</button>

    <script>
        const h2 = document.querySelector('h2')
        const btn = document.querySelector('button')
        let obj = {
            count: 1
        }
        let num = obj.count  // 防止递归爆栈

        function observer(val) {
            //找出页面上所有 用到了 count 这个变量的dom 结构 -- 找到订阅者
            // 将订阅者的内容替换为新的值
            h2.innerHTML = val
        }

        Object.defineProperty(obj, 'count', {
            get() {
                return num
            },
            set(val) {
                observer(val)
                num = val
            }
        })


        btn.addEventListener('click', () => {
            obj.count++
        })

    </script>
</body>

</html>